import { HttpException, HttpStatus, Injectable, UseFilters } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { isEmpty } from 'class-validator';
import { HttpExceptionFilter } from 'src/core/filter/http-exception.filter';
import { User } from 'src/user/entities/user.entity';
import { throwHttp } from 'src/util/util';
import { IsNull, Not, Repository } from 'typeorm';
import { CreateleaveAMessageDto, MessageRo } from './dto/message-board.dto';
import { UpdateMessageBoardDto } from './dto/update-message-board.dto';
import { MessageBoardEntity } from './entities/message-board.entity';

@Injectable()
export class MessageBoardService {
  constructor(
    @InjectRepository(MessageBoardEntity) private messageBoardRepository: Repository<MessageBoardEntity>,
  ) { }

  @UseFilters(new HttpExceptionFilter())
  async create(body: CreateleaveAMessageDto, { user, toUser }: { user: User; toUser: User }) {
    try {
      const { userId, content, messageBoardId, toUserId } = body
      const messageBoard = new MessageBoardEntity()
      messageBoard.user = user
      messageBoard.userId = userId
      messageBoard.content = content
      if (messageBoardId) {
        const messageBoardInfo = await this.getMessageBoardInfo(messageBoardId)
        if (messageBoardId && !isEmpty(messageBoardId)) {
          messageBoard.messageBoardId = messageBoardId
          messageBoard.messageBoard = messageBoardInfo
          messageBoard.toUser = toUser
          messageBoard.toUserId = toUserId
          messageBoard.parseId = await this.getParseId(messageBoard)
        }
      }
      const result = await this.messageBoardRepository.manager.save(messageBoard)
      return result
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
    }
  }

  // 获取用户信息
  @UseFilters(new HttpExceptionFilter())
  async getMessageBoardInfo(id: number): Promise<MessageBoardEntity> {
    try {
      const data = await this.messageBoardRepository.findOne({
        where: { id, },
      })
      if (!data) {
        throwHttp('留言不存在')
      }
      return data
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
    }
  }

  @UseFilters(new HttpExceptionFilter())
  async findAll(query): Promise<any> {
    try {
      const { pageNum = 1, pageSize = 10 } = query;
      const fatherResult = await this.messageBoardRepository.findAndCount({
        where: { messageBoardId: IsNull() },
        skip: (pageNum - 1) * pageSize,
        take: pageSize,
        order: { createTime: "DESC" },
        cache: true,
        relations: ['user'],
      })

      const parseIdList = fatherResult[0].map((item) => item.id)
      const sonResult = await this.messageBoardRepository.createQueryBuilder('messageBoard').where("messageBoard.parseId IN (:...parseIdList)", { parseIdList: parseIdList }).orderBy('messageBoard.createTime', 'DESC').getMany()
      // const sonResult = await this.messageBoardRepository.findAndCount({
      //   where:{parseId:Not(null)},
      //   skip:(pageNum - 1) * pageSize,
      //   take:pageSize,
      //   order:{createTime:"DESC"},
      //   cache:true,
      //   relations:['user'],
      // })
      const list = fatherResult[0].map((item) => item);
      const sonList = sonResult.map((item)=>item)
      return { list:list,sonList:sonList };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
    }
  }

  async findOne(id) {
    const result = await this.messageBoardRepository.findOne(id);
    if (!result)
      throw new HttpException(`id为${id}的评论不存在`, HttpStatus.BAD_REQUEST);
    return result;
  }


  update(id: number, updateMessageBoardDto: UpdateMessageBoardDto) {
    return `This action updates a #${id} messageBoard`;
  }

  remove(id: number) {
    return `This action removes a #${id} messageBoard`;
  }
  async getParseId(item) {
    let i = await this.findOne(item.messageBoardId)
    if (!i.messageBoardId) {
      return i.id

    } else {
      return this.getParseId(i)
    }
  }
}
